package com.luo.search.service.impl;

import com.example.bbs.front.service.IQuestionService;
import com.luo.common.exception.BBSServiceException;
import com.luo.common.restful.JsonPage;
import com.luo.common.restful.ResponseCode;
import com.luo.pojo.question.vo.QuestionVO;
import com.luo.pojo.search.QuestionForSearch;
import com.luo.search.repository.QuestionSearchRepository;
import com.luo.search.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SearchServiceImpl implements ISearchService {
    //查询出所有帖子
    @DubboReference
    private IQuestionService service;
    @Autowired
    private QuestionSearchRepository repository;

    @Override
    public JsonPage<QuestionForSearch> search(String keyword, Integer page, Integer pageSize) {
        if (page == null || pageSize==null){
            page = 1;
            pageSize = 10;
        }
        if (keyword == null){
            throw new BBSServiceException(ResponseCode.NOT_FOUND,"关键词不能为空！");
        }
        Page<QuestionForSearch> question = repository.search(keyword, PageRequest.of(page - 1, pageSize));
        if (question == null){
            return null;
        }
        JsonPage<QuestionForSearch> jsonPage = new JsonPage<>();
        jsonPage.setPage(page);
        jsonPage.setPageSize(pageSize);
        jsonPage.setTotalPage(question.getTotalPages());
        jsonPage.setTotal(question.getTotalElements());
        jsonPage.setList(question.getContent());
        return jsonPage;
    }

    @Override
    public void loadSpuByPage() {
        repository.deleteAll();
        int i = 1;
        int pages = 0;
        do {
            JsonPage<QuestionVO> questionJsonPage = service.getAll(i, 4);
            List<QuestionForSearch> list = new ArrayList<>();
            for (QuestionVO questionvo : questionJsonPage.getList()) {
                QuestionForSearch questionForSearch = new QuestionForSearch();
                BeanUtils.copyProperties(questionvo, questionForSearch);
                list.add(questionForSearch);
            }
            repository.saveAll(list);
            i++;
            pages = questionJsonPage.getTotalPage();
        } while (i <= pages);
    }
}
